<script setup>

import { ref,onMounted,computed, } from 'vue'
import axios from 'axios'
import { ElMessage  } from 'element-plus';
import AddressDialog from "@/components/AddressDialog.vue";
import { useRoute } from 'vue-router';
const route = useRoute();
import { useRouter } from 'vue-router'
const router = useRouter();
import { userStore } from '@/store/index.js'
const store = userStore()

const addressId = ref(0);    //要提交的收货地址，也是默认选中的地址
const addresses = ref([]);   //显示地址列表
const cart = ref({});        //购物车

//修改收货地址
const changeAddress = (addressId)=>{
  addressId.value = addressId;
}
//查询当前用户的所有收货地址
const initAddress = ()=> {
  axios.get("/address/findAddress").then(resp => {
    addresses.value = resp.data;
    console.log("所有地址",addresses.value)
    //获取默认选中的地址id
    addresses.value.forEach(item => {
      if (item.isDefault == 1) {
        addressId.value = item.id;
      }
    });
  })
}
const dialogVisible = ref(false)
const showAddressDialog = ()=>{
  dialogVisible.value = true
}
//关闭对话框
const handleAddClose = (val)=> {
  //修改外部的值
  dialogVisible.value = val;
}


//获取购物车数据
const initCart = ()=>{
  axios.get("/cart/getCart").then(resp => {
    cart.value = resp.data;
  })
}
const disabled = ref(false)    //提交按钮不可用
//提交订单
const submitOrder = ()=>{
  axios.post(`/orders/createByBuy/${addressId.value}`,selectedItems.value).then(resp => {
    disabled.value = true;
    //可以设置提交按钮不可用，5秒后再还原
    setTimeout(() => {
      disabled.value = false;
    }, 5000);
    ElMessage.success(resp.data);
    //过1秒后再跳转
    setTimeout(() => {
      //跳转到订单列表页面
      router.push('/myOrder/').catch(error => error);
    }, 1000);
  }).catch(error => {
    //输出错误信息
    ElMessage.error(error.response.data);
  });
}

const goAddress=()=>{
  router.push("/myCenter/address").catch(error => error);
}
const selectedItems = ref({});

const selectedAmount = computed(() => {
  if (!selectedItems.value) {
    return 0;
  }
  return selectedItems.value.quantity || 0;
});

const selectedTotalPrice = computed(() => {
  if (!selectedItems.value) {
    return 0;
  }
  return selectedItems.value.sumPrice || 0;
});

// const selectedAmount = computed(() => {
//   return selectedItems.value.reduce((sum, item) => sum + item.quantity, 0);
// });
//
// const selectedTotalPrice = computed(() => {
//   return selectedItems.value.reduce((total, item) => total + item.sumPrice, 0);
// });

onMounted(()=>{
  initAddress()
  initCart();
  const selectedItemsData = route.query.selectedItems;
  if (selectedItemsData) {
    selectedItems.value = JSON.parse(selectedItemsData);
    console.log("跳转过来携带的数据",selectedItems.value)
  }
  // if (selectedItemsData) {
  //   try {
  //     const parsedData = JSON.parse(selectedItemsData);
  //     if (typeof parsedData === 'object') {
  //       selectedItems.value = parsedData;
  //       console.log("跳转过来携带的数据", selectedItems.value);
  //     } else {
  //       console.error('Invalid data format:', parsedData);
  //     }
  //   } catch (error) {
  //     console.error('Error parsing selectedItems:', error);
  //     console.error('Invalid JSON string:', selectedItemsData);
  //   }
  // }
})


</script>

<template>
  <div class="main">
    <h1>订单结算</h1>
    <el-tag>收货地址</el-tag>
    <el-button type="warning" size="small" @click="goAddress">去修改收货地址</el-button>
    <el-select v-model="addressId" placeholder="请选择收货地址" style="width: 400px" size="small">
      <el-option v-for="item in addresses"
                 :key="item.id" :value="item.id"
                 :label="item.allAddress + item.telephone + item.receiver"
                 @change="changeAddress">
        <div>
          <div>【{{item.allAddress}}】 {{item.telephone}} {{item.receiver}}</div>
<!--          <el-button type="text" @click.stop="showEditDialog(item)">修改</el-button>-->
<!--          <div>:label="item.allAddress"</div>-->
        </div>
      </el-option>
    </el-select>
    <el-button style="margin-left: 10px;" type="success" @click="showAddressDialog" size="small">新增收货地址</el-button>

    <el-card class="cart">
      <el-table :data="[selectedItems]" style="width: 100%" stripe highlight-current-row
                class="cart-table">
        <el-table-column type="index" width="55" label="序号">
          <template #default="{$index}">{{ $index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="name" label="商品">
          <template #default="{row}">
            {{ row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="image" label="图片">
          <template #default="{row}">
            <el-image style="height: 120px;"
                      :src="$urlImage + row.imgSrc"
                      fit="fit">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价">
          <template #default="{row}">
            &yen; {{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量">
          <template #default="{row}">
            <el-tag type="danger">{{ row.quantity }}件</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sumPrice" label="金额">
          <template #default="{row}">
            &yen; {{ row.sumPrice.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <span>共有<span class="cart-number">{{ selectedAmount }}</span>件商品</span>
        <span>合计：<span style="color: red; font-size: 25px;">
                   &yen; {{selectedTotalPrice ? selectedTotalPrice.toFixed(2) : 0}}</span>
        </span>
        <el-button type="primary" @click="submitOrder" :disabled="disabled">提交订单</el-button>
      </div>
    </el-card>


    <!-- 新增收货地址 -->
    <AddressDialog :dialogVisible="dialogVisible" @reload-address="initAddress"
                   @close="handleAddClose"/>

  </div>
</template>

<style scoped>
.main {
  padding: 5px;
}


.cart {
  margin-top: 10px;
}

.cart-table {
  border-radius: 10px;
}

.cart-footer {
  margin-top: 10px;
  text-align: right;
}

.cart-footer > * {
  margin: 10px;
}

.cart-number {
  color: red;
  font-size: 22px;
}
</style>